/**
 * Copyright (C) 2018-2022
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制
 */
package co.yixiang.modules.mp.serviceimpl;


import cn.hutool.core.util.ObjectUtil;
import co.yixiang.common.exception.ServiceException;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.utils.FileUtil;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.modules.mp.entity.domain.YxArticle;
import co.yixiang.modules.mp.entity.domain.YxHelp;
import co.yixiang.modules.mp.entity.dto.YxHelpDto;
import co.yixiang.modules.mp.entity.dto.YxHelpQueryCriteria;
import co.yixiang.modules.mp.entity.vo.YxArticleVo;
import co.yixiang.modules.mp.entity.vo.YxHelpVo;
import co.yixiang.modules.mp.mapper.HelpMapper;
import co.yixiang.modules.mp.service.YxHelpCategoryService;
import co.yixiang.modules.mp.service.YxHelpService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
 * @author hupeng
 * @date 2020-05-12
 */
@Slf4j
@Service
//@CacheConfig(cacheNames = "YxHelp")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxHelpServiceImpl extends BaseServiceImpl<HelpMapper, YxHelp> implements YxHelpService {
    @Autowired
    private IGenerator generator;
    @Value("${file.path}")
    private String uploadDirStr;
    @Autowired
    private YxHelpCategoryService helpCategoryService;


    @Override
    public Map<String, Object> queryAllToVo(YxHelpQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<YxHelp> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), YxHelpVo.class));
        map.put("totalElements", page.getTotal());
        return map;
    }

    @Override
    public YxHelpVo readHelpVo(Integer id) {
        final YxHelp article = getById(id);
        if (ObjectUtil.isEmpty(article)) {
            throw new ServiceException("没有id为:" + id + "的帮助信息");
        }
        // 增加浏览记录
        article.setVisit(article.getVisit() + 1);
        this.updateById(article);
        return generator.convert(article, YxHelpVo.class);
    }

    @Override
    public Map<String, Object> queryAll(YxHelpQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<YxHelp> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), YxHelpDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    public List<YxHelp> queryAll(YxHelpQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(YxHelp.class, criteria));
    }

    @Override
    public YxHelpDto findById(YxHelpQueryCriteria criteria) {
        // 查询到文章信息
        final YxHelp article = getById(criteria.getId());
        return generator.convert(article, YxHelpDto.class);
    }


    @Override
    public void download(List<YxHelpDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YxHelpDto help : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("分类id", help.getCid());
            map.put("问题标题", help.getTitle());
            map.put("描述", help.getDescribe());
            map.put("content", help.getContent());
            map.put("浏览次数", help.getVisit());
            map.put("排序", help.getSort());
            map.put("添加时间", help.getCreateTime());
            map.put("是否隐藏", help.getHide());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void uploadNews(YxHelpDto helpDto) throws WxErrorException {

//        WxMpService wxMpService = WxMpConfiguration.getWxMpService();
//
//        WxMpMaterialNews wxMpMaterialNews = new WxMpMaterialNews();
//
//
//        WxMpNewsArticle article = new WxMpNewsArticle();
//        //处理content
//        String content = processContent(wxMpService, helpDto.getContent());
//        System.out.println(content);
//        article.setContent(content);
//        article.setDigest(helpDto.getDescribe());
//        article.setShowCoverPic(true);
//        article.setTitle(helpDto.getTitle());
//        //TODO 暂时注释掉，测试号没有留言权限
//        //article.setNeedOpenComment( wxNewsArticleItem );
//        //article.setOnlyFansCanComment( wxNewsArticleItem );
//        wxMpMaterialNews.addArticle(article);
//
//        log.info("wxMpMaterialNews : {}", JSONUtil.toJsonStr(wxMpMaterialNews));
//
//        WxMpMaterialUploadResult wxMpMaterialUploadResult1 = wxMpService.getMaterialService()
//                .materialNewsUpload(wxMpMaterialNews);
//
//        //推送开始
//        WxMpMassTagMessage massMessage = new WxMpMassTagMessage();
//        massMessage.setMsgType(WxConsts.MassMsgType.MPNEWS);
//        massMessage.setMediaId(wxMpMaterialUploadResult1.getMediaId());
//        massMessage.setSendAll(true);
//
//        WxMpMassSendResult massResult = wxMpService.getMassMessageService()
//                .massGroupMessageSend(massMessage);
//        if (!"0".equals(massResult.getErrorCode())) {
//            log.info("error:" + massResult.getErrorMsg());
//            throw new ErrorRequestException("发送失败");
//        }
//
//        log.info("massResult : {}", JSONUtil.toJsonStr(massResult));
//
//        log.info("wxMpMaterialUploadResult : {}", JSONUtil.toJsonStr(wxMpMaterialUploadResult1));
    }

    @Override
    public void update(YxHelp resources) {
        updateById(resources);
    }

    @Override
    public Object create(YxHelp resources) {

        return save(resources);
    }
}
